import 'dart:async';

import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

enum ViewState {
  idle, //空闲
  busy, //加载中
  empty, //无数据
  error, //错误
}

class BaseViewModel with ChangeNotifier {
  bool _disposed = false;
  ViewState _viewState = ViewState.idle;
  late BuildContext context;
  bool autoLoadData = true;
  StreamSubscription? stream;

  final RefreshController _refreshController = RefreshController();

  RefreshController get refreshController => _refreshController;

  BaseViewModel({ViewState? viewState}) {
    _viewState = viewState ?? ViewState.idle;
  }

  ViewState get viewState => _viewState;

  bool get isIdle => viewState == ViewState.idle;

  bool get isBusy => viewState == ViewState.busy;

  bool get isEmpty => viewState == ViewState.empty;

  bool get isError => viewState == ViewState.error;

  void setBuildContext(BuildContext context) {
    this.context = context;
  }

  set viewState(ViewState value) {
    _viewState = value;
    if (value != ViewState.busy) notifyListeners();
  }

  void setIdle() {
    viewState = ViewState.idle;
  }

  void setBusy() {
    viewState = ViewState.busy;
  }

  void setEmpty() {
    viewState = ViewState.empty;
  }

  void setError() {
    viewState = ViewState.error;
  }

  @override
  void notifyListeners() {
    if (!_disposed) super.notifyListeners();
  }

  @override
  void dispose() {
    _disposed = true;
    stream?.cancel();
    stream = null;
    super.dispose();
  }

  void initState() {}
}
